# coding=utf-8
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from tensorflow.python.tools import freeze_graph
import argparse
import logging
import tensorflow as tf
from experiments.run_context import RunContext
from mean_teacher.model import Model

logging.basicConfig(level=logging.INFO)
LOG = logging.getLogger('main')
parser = argparse.ArgumentParser()
parser.add_argument('--ckpt_path',type=str, default='./ckpt/checkpoint-40000',help='The path of checkpoint')


#running function
def run(args):
    ckpt_path = args.ckpt_path
    model = Model(RunContext(__file__, 0, './output'))

    LOG.info("Saved tensorboard graph to ./pb_model")


    logits = model.class_logits_ema
    output = tf.argmax(logits, -1, output_type=tf.int32, name="output") #output node will be used to inference
    with tf.Session() as sess:
        tf.train.write_graph(sess.graph_def, './pb_model', 'output_empty.pb')  # save pb file with output node
        freeze_graph.freeze_graph(
            input_graph='./pb_model/output_empty.pb',  # the pb file with output node
            input_saver='',
            input_binary=False,
            input_checkpoint=ckpt_path,  # input checkpoint file path
            output_node_names='output',  # the name of output node in pb file
            restore_op_name='save/restore_all',
            filename_tensor_name='save/Const:0',
            output_graph='./pb_model/mean-teacher.pb',  # path of output graph
            clear_devices=False,
            initializer_nodes='')
    logging.info('done')
if __name__ == "__main__":
    args = parser.parse_args()
    run(args)

    
